<template>
  <div class="workorder-list-container">
    <div class="workorder-list-title">维修单管理</div>
    <div class="search-bar">
      <el-input v-model="searchQuery" placeholder="请输入工单编号或设备名称搜索" class="search-input">
        <template #append>
          <el-button type="primary" @click="fetchWorkorders">搜索</el-button>
        </template>
      </el-input>
      <el-button type="success" @click="addWorkorder" class="add-btn">新增维修单</el-button>
    </div>
    <el-table :data="workorderList" style="width: 100%">
      <el-table-column prop="id" label="工单编号" width="100"></el-table-column>
      <el-table-column prop="deviceName" label="设备名称"></el-table-column>
      <el-table-column prop="deviceModel" label="设备型号" width="120"></el-table-column>
      <el-table-column prop="username" label="用户名称"></el-table-column>
      <el-table-column prop="faultDescription" label="故障描述"></el-table-column>
      <el-table-column prop="status" label="工单状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="repairmanName" label="维修人员" width="120"></el-table-column>
      <el-table-column prop="createTime" label="提交时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewDetails(scope.row)">查看</el-button>
          <el-button size="small" type="primary" @click="editWorkorder(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteWorkorder(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import service from '~/axios';
import { toast, showModal } from '~/composables/util';
import { getToken } from '~/composables/auth';

const router = useRouter();
const workorderList = ref([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

onMounted(() => {
  if (!getToken()) {
    toast('请先登录', 'warning');
    router.push('/admin-login');
    return;
  }

  fetchWorkorders();
});

const fetchWorkorders = async () => {
  try {
    const res = await service.get('/api/admin/workorders', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value
      }
    });
    workorderList.value = res.list;
    total.value = res.total;
  } catch (error) {
    toast('获取维修单列表失败，请稍后重试', 'error');
  }
};

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status] || status;
};

const getStatusTagType = (status) => {
  const typeMap = {
    'pending': 'info',
    'processing': 'warning',
    'completed': 'success',
    'cancelled': 'danger'
  };
  return typeMap[status] || 'default';
};

const viewDetails = (row) => {
  router.push({ path: '/admin/workorder-detail', query: { id: row.id } });
};

const editWorkorder = (row) => {
  router.push({ path: '/admin/workorder-edit', query: { id: row.id } });
};

const addWorkorder = () => {
  router.push('/admin/workorder-add');
};

const deleteWorkorder = async (row) => {
  try {
    await showModal(`确定要删除工单 ${row.id}?`, 'danger');
    await service.post('/api/admin/delete-workorder', { id: row.id });
    toast('删除成功');
    fetchWorkorders();
  } catch (error) {
    // 用户取消删除
  }
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchWorkorders();
};

const handleCurrentChange = (current) => {
  currentPage.value = current;
  fetchWorkorders();
};
</script>

<style scoped>
.workorder-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.workorder-list-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>